package controllers

import (
	"encoding/json"
	"fmt"
	"time"

	"cvevulner/common"
	"cvevulner/errcode"
	"cvevulner/models"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type UserLoginController struct {
	beego.Controller
}

type Result struct {
	Key    string      `json:"Token"`
	UserId interface{} `json:"UserId"`
}

func (c *UserLoginController) RetData(resp map[string]interface{}) {
	c.Data["json"] = resp
	c.ServeJSON()
}

// @Title UserLogin
// @Description UserLogin
// @Param	body		body 	models.User	true		"body for user content"
// @Success 200 {int} models.User.ID
// @Failure 403 body is empty
// @router / [post]
func (u *UserLoginController) Post() {
	req := make(map[string]interface{})
	resp := make(map[string]interface{})
	resp["errno"] = errcode.RecodeLoginErr
	resp["errmsg"] = errcode.RecodeText(errcode.RecodeLoginErr)
	resp["body"] = Result{}
	//defer u.RetData(resp)
	err := json.Unmarshal(u.Ctx.Input.RequestBody, &req)
	if err != nil {
		logs.Error(err)
		u.RetData(resp)
		return
	}
	//Judge whether it is legal
	if req["userName"] == nil || req["passWord"] == nil {
		resp["errno"] = errcode.RecodeDataErr
		resp["errmsg"] = errcode.RecodeText(errcode.RecodeDataErr)
		resp["body"] = Result{}
		logs.Error("Data error: username or password")
		u.RetData(resp)
		return
	}
	password := fmt.Sprintf("%s", req["passWord"])
	// Encryption first comment
	password = common.DesString(password)
	if password == "" || len(password) == 0 {
		resp["errno"] = errcode.RecodePwdErr
		resp["errmsg"] = errcode.RecodeText(errcode.RecodePwdErr)
		logs.Error("Password parsing error.")
		resp["body"] = Result{}
		u.RetData(resp)
		return
	}
	var strc Result
	username := fmt.Sprintf("%s", req["userName"])
	respModel, err := models.GetCveUserByUser(username, password)
	logs.Info(respModel)
	if respModel != nil && err == nil {
		if exp, ok := respModel[0]["expiration_time"].(string); ok && exp > models.Time2Str() {
			if k, kok := respModel[0]["aes_key"].(string); kok {
				strc.Key = k
				strc.UserId = respModel[0]["user_id"]
				resp["body"] = strc
				resp["errno"] = errcode.RecodeOk
				resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
				u.RetData(resp)
				return
			}
		}
		token, terr := common.GenToken(username, password)
		if terr == nil {
			strc.Key = token
			logs.Info(respModel[0]["user_id"])
			userId := respModel[0]["user_id"]
			strc.UserId = userId
			resp["body"] = strc
			resp["errno"] = errcode.RecodeOk
			resp["errmsg"] = errcode.RecodeText(errcode.RecodeOk)
			expirTime := common.GetTokenExpirTime()
			newTime := time.Now().AddDate(0, 0, expirTime)
			models.UpdateToken(respModel[0]["user_id"], token, newTime)
			u.RetData(resp)
			return
		}
	}
	u.RetData(resp)
	return
}
